﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

using System.Management;    //需要引用System.Management.dll
using Microsoft.Win32;

using System.Diagnostics;

using Helper;
using RegisterKey;

namespace PanelIDOCR
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll", EntryPoint = "Beep")]
        // 第一个参数是指频率的高低，越大越高，第二个参数是指响的时间多长  
        public static extern int Beep(int dwFreq, int dwDuration);

        [DllImport("user32.dll")]
        public static extern int MessageBeep(uint uType);
        uint beepI = 0x00000030;
        
        public Form1()
        {
            InitializeComponent();
            comboBox2.Items.Add("无");
            comboBox2.Items.Add("字符数量对不上");
            comboBox2.Items.Add("字符内容不一样");
            comboBox2.Items.Add("产品码破损严重");
            comboBox2.SelectedIndex = 0;
            MessageBeep(beepI);
            //Beep(100, 1000);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string text12 = e.ToString();
            //if (text12 != "System.Windows.Forms.MouseEventArgs") return;//屏蔽enter键输入
            //if (e == System.EventArgs) return;
            string text1 = label3.Text;
            string text2 = textBox1.Text;
            string text3 = textBox2.Text;
            string text4 = "";
            string text5;
            if (text2 == text3)
            {
                text5 = "OK";
                label7.BackColor = Color.Green;
            }
            else if(text3.Length < text2.Length)
            {
                text5 = "UNKNOW";
                label7.BackColor = Color.YellowGreen;
            }
            else
            {
                int n = text2.Length /*> text3.Length ? text3.Length : text2.Length*/;/*获得较短的字符串的长度*/
                for (int i = 0; i < n; i++)
                {
                    string text = "";
                    if(text3.Length > i) text = text3.Substring(i, 1);
                    if (text2.Substring(i, 1) != text)
                    {
                        text4 += text2.Substring(i, 1);
                    }
                }

                //Beep(100, 1000);
                MessageBeep(beepI);
                text5 = "NG";
                label7.BackColor = Color.Red;
            }

            string text6 = comboBox2.SelectedItem.ToString();
            string text7 = textBox3.Text;

            string[] row1 = new string[] { text1, text2, text3, text4, text5, text6, text7 };

            label7.Text = text5;
            dataGridView1.Rows.Add(row1);

            textBox1.Text = "";
            textBox2.Text = "";
            textBox1.Focus();

            dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);

            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                if (this.dataGridView1.Rows[i].Cells["Column4"].Value == "NG")
                {
                    this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                }
                else if(this.dataGridView1.Rows[i].Cells["Column4"].Value == "OK")
                {

                    this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                }
                else 
                {
                    this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.YellowGreen;
                }

            }

            
            OkNgClearAsync();
            Save_Excel();
        }

        private async void OkNgClearAsync()
        {
            int delayTime = 3000;
            string textTime = textBox4.Text;
            if (textTime != "")
            {
                delayTime = int.Parse(textTime) * 1000;
            }
            await Task.Delay(delayTime);      //执行到await表达式时，立即返回到调用方法，等待5秒后执行后续部分
            label7.BackColor = Color.White;
            label7.Text = "";
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dataGridView1.RowHeadersWidth - 4,
                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label3.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label7.BackColor = Color.White;
            label7.Text = "";

            this.Resize += new EventHandler(MainForm_Resize);
            MainFormOldWidth = this.Width;
            MainFormOldHeight = this.Height;
            setTag(this);//存储控件的信息

            string sUri = "https://www.baidu.com/";

            saveFileName = System.IO.Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xlsx";
            // 如果文件存在，则读取相应的参数信息
            string configPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + ".ini";
            string Keytext = "";
            if (File.Exists(configPath))
            {
                this.textBox3.Text = IniConfigHelper.ReadIniData("PanelIDOCR参数", "User", "", configPath);
                this.textBox4.Text = IniConfigHelper.ReadIniData("PanelIDOCR参数", "延时", "3", configPath);
                sUri = IniConfigHelper.ReadIniData("PanelIDOCR参数", "网址", "https://www.baidu.com/", configPath);
                Keytext = IniConfigHelper.ReadIniData("注册", "Key", "", configPath);
            }

            this.timer1.Interval = 1000;//设置timer1的Interval属性为1000，即计时器开始计时之间的间隔为1000ms
            this.timer1.Start();//启动计时器

            //this.webBrowser1.Navigate("https://www.baidu.com/");

            this.webBrowser1.Url = new Uri(sUri);
            this.webBrowser1.ScriptErrorsSuppressed = true;



            //判断软件是否注册
            RegistryKey retkey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true).CreateSubKey("PanelIDOCR").CreateSubKey("RegisterInfo");
            foreach (string strRNum in retkey.GetSubKeyNames())
            {
                if (strRNum == softReg.GetRNum())
                {
                    this.labRegInfo.Text = "此软件已注册！";
                    this.btnReg.Enabled = false;
                    this.btnReg.Visible = false;
                    return;
                }
            }
            this.labRegInfo.Text = "此软件尚未注册！";
            this.btnReg.Enabled = true;
            MessageBox.Show("您现在使用的是试用版，可以免费试用30次！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);


            Int32 tLong;    //已使用次数
            try
            {
                tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\PanelIDOCR", "UseTimes", 0);
                MessageBox.Show("您已经使用了" + tLong + "次！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("欢迎使用本软件！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\PanelIDOCR", "UseTimes", 0, RegistryValueKind.DWord);
            }


            //判断是否可以继续试用
            tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\PanelIDOCR", "UseTimes", 0);
            if (tLong < 30)
            {
                int tTimes = tLong + 1;
                Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\PanelIDOCR", "UseTimes", tTimes);
            }
            else
            {
                DialogResult result = MessageBox.Show("试用次数已到！您是否需要注册？", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    FormRegister.state = false; //设置软件状态为不可用
                    btnReg_Click(sender, e);    //打开注册窗口
                }
                else
                {
                    Application.Exit();
                }
            }

            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string fileName = "";
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xlsx";
            saveDialog.Filter = "Excel文件|*.xlsx";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0)
                return ; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，您的电脑可能未安装Excel");
                return ;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            //写入标题             
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; 
            }
            //写入数值
            for (int r = 0; r < dataGridView1.Rows.Count; r++)
            {
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
                }
                catch (Exception ex)
                {//fileSaved = false;                      
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            Kill(xlApp);
            GC.Collect();//强行销毁      
            return ;
        }

        private void Save_Excel()
        {
            if (dataGridView1.Rows.Count == 0)
            {
                return;
            }
            //string fileName = "";
            //saveFileName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xlsx"; 

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，您的电脑可能未安装Excel");
                return;
            }
            object MisValue = Type.Missing;

            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 

            //写入标题             
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < dataGridView1.Rows.Count; r++)
            {
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }

            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
                }
                catch (Exception ex)
                {//fileSaved = false;                      
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }


            xlApp.Quit();
            Kill(xlApp);
            GC.Collect();//强行销毁      
            return;
        }

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
        {
            IntPtr t = new IntPtr(excel.Hwnd);
            int k = 0;
            GetWindowThreadProcessId(t, out k);
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();
        }

         private void button3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否清除数据", "Confirm Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                dataGridView1.Rows.Clear();
                saveFileName = System.IO.Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xlsx";
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string configPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + ".ini";
            // 如果文件不存在则创建文件后再保存
            if (!File.Exists(configPath))
            {
                FileStream fileStream = new FileStream(configPath, FileMode.Create);
                fileStream.Close();
            }
            IniConfigHelper.WriteIniData("PanelIDOCR参数", "User", this.textBox3.Text.Trim(), configPath);
            IniConfigHelper.WriteIniData("PanelIDOCR参数", "延时", this.textBox4.Text.Trim(), configPath);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                textBox2.Focus(); //当在文本框1中检查到回车键时，直接将焦点转入TextBox2
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                textBox1.Focus(); //当在文本框1中检查到回车键时，直接将焦点转入TextBox2
                button1_Click(sender, e);
            }
        }

        SoftReg softReg = new SoftReg();

        private void btnReg_Click(object sender, EventArgs e)
        {
            FormRegister frmRegister = new FormRegister();
            frmRegister.ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox1.Focus();

            label7.BackColor = Color.White;
            label7.Text = "";
        }

        private string saveFileName;

        private void Form1_MaximumSizeChanged(object sender, EventArgs e)
        {
            
        }

        private float MainFormOldWidth;
        private float MainFormOldHeight;
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
                if (con.Controls.Count > 0)
                    setTag(con);
            }
        }

        /// <summary>
        /// 设置对应控件的大小
        /// </summary>
        /// <param name="newx">窗体长</param>
        /// <param name="newy">窗体宽</param>
        /// <param name="cons">控件</param>
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
                float a = Convert.ToSingle(mytag[0]) * newx;
                con.Width = (int)a;
                a = Convert.ToSingle(mytag[1]) * newy;
                con.Height = (int)(a);
                a = Convert.ToSingle(mytag[2]) * newx;
                con.Left = (int)(a);
                a = Convert.ToSingle(mytag[3]) * newy;
                con.Top = (int)(a);
                Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy);
                con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                if (con.Controls.Count > 0)
                {
                    setControls(newx, newy, con);
                }
            }
        }


        /// <summary>
        /// 窗体大小改变，获取窗体的长宽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / MainFormOldWidth;
            float newy = (this.Height) / MainFormOldHeight;
            setControls(newx, newy, this);
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            
            //int i = 0;
        }

        private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
        {
            //判断按键是不是要输入的类型。
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                e.Handled = true;

            //小数点的处理。
            if ((int)e.KeyChar == 46)                           //小数点
            {
                if (textBox1.Text.Length <= 0)
                    e.Handled = true;   //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(textBox1.Text, out oldf);
                    b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (webBrowser1.ReadyState != WebBrowserReadyState.Complete) return;
            Size szb = new Size(webBrowser1.Document.Body.OffsetRectangle.Width,
            webBrowser1.Document.Body.OffsetRectangle.Height);
            Size sz = webBrowser1.Size;

            int xbili = (int)((float)sz.Width / (float)szb.Width * 100);//水平方向缩小比例
            int ybili = (int)((float)sz.Height / (float)szb.Height * 100);//垂直方向缩小比例
            //webBrowser1.Document.Body.Style = "zoom:" + sz.ToString() + "%";//也可以直接设置
            webBrowser1.Document.Body.Style = "zoom:" + ybili.ToString() + "%";//也可以直接设置
            webBrowser1.Invalidate();
        }
    }
}
